package com.github.binarywang.demo.wx.mp.handler;

import cn.xsshome.taip.nlp.TAipNlp;
import cn.xsshome.taip.ocr.TAipOcr;
import com.github.binarywang.demo.wx.mp.builder.TextBuilder;
import com.github.binarywang.demo.wx.mp.utils.ApacheMediaDownloadNOFileRequestExecutor;
import com.github.binarywang.demo.wx.mp.utils.ImageUtils;
import com.github.binarywang.demo.wx.mp.utils.JsonUtils;
import com.github.binarywang.demo.wx.mp.utils.WxAIError;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.impl.WxMpServiceHttpClientImpl;
import me.chanjar.weixin.mp.bean.material.WxMediaImgUploadResult;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutNewsMessage;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import me.chanjar.weixin.mp.builder.outxml.NewsBuilder;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.*;

import static me.chanjar.weixin.common.api.WxConsts.XmlMsgType;

/**
 * @author Binary Wang(https://github.com/binarywang)
 */
@Component
public class MsgHandler extends AbstractHandler {

    @Value("${wx.ai.AIID}")
    String AIID ;
    @Value("${wx.ai.AIKey}")
    String AIKey;
    @Value("${wx.pg.tmpDirFile}")
    String tmpDirFile;
    @Value("${wx.pg.template_id}")
    String template_id;


    @Override
    public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage,
                                    Map<String, Object> context, WxMpService weixinService,
                                    WxSessionManager sessionManager) {

        if (!wxMessage.getMsgType().equals(XmlMsgType.EVENT)) {
            //TODO 可以选择将消息保存到本地
        }

        if (wxMessage.getMsgType().equals(XmlMsgType.IMAGE)) {
            //TODO 可以选择将消息保存到本地
            String content = "照片已收到，随后会发送通知消息";

            getemplateMessage(wxMessage,context,weixinService,sessionManager);
            return new TextBuilder().build(content, wxMessage, weixinService);

        }

        //当用户输入关键词如“你好”，“客服”等，并且有客服在线时，把消息转发给在线客服
        try {
            if (StringUtils.startsWithAny(wxMessage.getContent(), "你好", "客服")
                && weixinService.getKefuService().kfOnlineList()
                .getKfOnlineList().size() > 0) {
                return WxMpXmlOutMessage.TRANSFER_CUSTOMER_SERVICE()
                    .fromUser(wxMessage.getToUser())
                    .toUser(wxMessage.getFromUser()).build();
            }
        } catch (WxErrorException e) {
            e.printStackTrace();
        }

        //TODO 组装回复消息

        TAipNlp client = new TAipNlp(this.AIID, this.AIKey);
        String text = wxMessage.getContent();
        String session = new Date().getTime()/1000+"";//会话标识（应用内唯一）
        //String result = client.nlpTextchat(text);//基础闲聊
        String result = null;//基础闲聊
        try {
            result = client.nlpTextchat(session,text);
        } catch (Exception e) {
            e.printStackTrace();
        }

//"收到信息内容：" + JsonUtils.toJson(wxMessage)+"\n 提供的回复："+
        String content = result;

        return new TextBuilder().build(content, wxMessage, weixinService);

    }

    /**
     *   comment by lidong
     *    将用户上传的图片识别后，以图文形式返回。
     *    但这里有微信的一个坑，微信会控制响应时间，如果查询慢，给响应后，微信不回报错，但也不会给用户发送信息。
     *    所以，采用模板消息通知的方式进行。
     */
    public WxMpXmlOutMessage getNews(String result,WxMpXmlMessage wxMessage) {
        //JsonObject tmpJsonObject = JSON_PARSER.parse(result).getAsJsonObject();
        this.logger.info("\n-----------------腾讯ocr返回结果-result:"+result);
        WxAIError  wxAIError = WxAIError.fromJson(result);
        List<WxMpXmlOutNewsMessage.Item> articles = new ArrayList<>();
        Map<String, String> hashMap = wxAIError.getData();
        WxMpXmlOutNewsMessage.Item item= new WxMpXmlOutNewsMessage.Item();
        item.setDescription("111111");
        item.setPicUrl(hashMap.get("imgUploadUrl"));
        item.setTitle(hashMap.get("name"));
        item.setUrl("www.baidu.com");
        articles.add(item);

        return new NewsBuilder().fromUser(wxMessage.getToUser()).toUser(wxMessage.getFromUser()).articles(articles).build();
    }

    /**
     *   comment by lidong
     *    将用户上传的图片识别后，以图文形式返回。
     *    但这里有微信的一个坑，微信会控制响应时间，如果查询慢，给响应后，微信不回报错，但也不会给用户发送信息。
     *    所以，采用模板消息通知的方式进行。
     *
     *    进行消息通知。
     */
    public void getemplateMessage(WxMpXmlMessage wxMessage,
                                  Map<String, Object> context, WxMpService weixinService,
                                  WxSessionManager sessionManager) {
        Map<String, String> result = getID(wxMessage,weixinService);

        try {
            WxMpTemplateMessage wxTemplateMessage = new WxMpTemplateMessage();
            wxTemplateMessage.setToUser(wxMessage.getFromUser());
            wxTemplateMessage.setTemplateId(this.template_id);
            wxTemplateMessage.setUrl(result.get("imgUploadUrl"));
            String tradeDateTime = "";
            try {
                Date date = new Date();
                tradeDateTime = new SimpleDateFormat("yyyy年MM月dd日 HH:mm").format(date);
            } catch (Exception e) {
                this.logger.error("时间转换失败！,openId:" + wxMessage.getToUser());
            }

            String type = "身份证OCR";
            String number = "免费";
            String outset = "尊敬的"+result.get("name")+"，您有新的交易信息！";
            String mainBoby = "证件类型：身份证\n" + "证件号码："+result.get("id")+"\n";
            String remark = "地址："+result.get("address")+"\n" + "出生日期："+result.get("birth")+"\n";
            WxMpTemplateData datum1 = new WxMpTemplateData("first", outset, "#173177");
            WxMpTemplateData datum2 = new WxMpTemplateData("productType", mainBoby, "#173177");
            WxMpTemplateData datum3 = new WxMpTemplateData("time", tradeDateTime, "#173177");
            WxMpTemplateData datum4 = new WxMpTemplateData("type", type, "#173177");
            WxMpTemplateData datum5 = new WxMpTemplateData("number", number, "#173177");
            WxMpTemplateData datum6 = new WxMpTemplateData("remark", remark, "#173177");
            wxTemplateMessage.addData(datum1);
            wxTemplateMessage.addData(datum2);
            wxTemplateMessage.addData(datum3);
            wxTemplateMessage.addData(datum4);
            wxTemplateMessage.addData(datum5);
            wxTemplateMessage.addData(datum6);

            String msgid = weixinService.getTemplateMsgService().sendTemplateMsg(wxTemplateMessage);
            this.logger.info("发送完成！,msgid:" + msgid);
        } catch (WxErrorException e) {
            e.printStackTrace();
        }
    }
    public  Map<String, String>  getID(WxMpXmlMessage wxMessage, WxMpService weixinService) {
        TAipOcr client = new TAipOcr(this.AIID, this.AIKey);
        Map map = wxMessage.getAllFieldsMap();
        String picUrl = map.get("PicUrl").toString();
        String tmpDirFile = this.tmpDirFile;
        File tmpDirFile1 = new File(tmpDirFile);

        ApacheMediaDownloadNOFileRequestExecutor simpleGetRequestExecutor = new ApacheMediaDownloadNOFileRequestExecutor((WxMpServiceHttpClientImpl) weixinService, tmpDirFile1);
        List<WxMpXmlOutNewsMessage.Item> articles = new ArrayList<>();
        this.logger.info("\n-----------------进入MsgHandler处理器");
        this.logger.info("\n-----------------PicUrl:" + picUrl);
        Map<String, String> hashMap = new HashMap<String, String>();


        try {
            File IDfile = simpleGetRequestExecutor.execute(picUrl, null);
            //String result = client.idcardOcr(picUrl1.getPath(), 0);//身份证正面(图片)识别;
            String result = client.idcardOcr(IDfile.getPath(), 0);//身份证反面(国徽)识别;
            this.logger.info("\n-----------------腾讯ocr返回结果-result:" + result);
            WxAIError wxAIError = WxAIError.fromJson(result);
            this.logger.info("\n-----------------腾讯ocr返回结果-json转换msg:" + wxAIError.getMsg());
            this.logger.info("\n-----------------腾讯ocr返回结果-json转换ret:" + wxAIError.getRet());
            this.logger.info("\n-----------------腾讯ocr返回结果-json转换data:" + wxAIError.getData());
            hashMap = wxAIError.getData();
        } catch (Exception e) {
        }

        //-----------------------------将返回的身份证图片保存--------------------------
        String frontimage =hashMap.get("frontimage").replaceAll("\"","");
        String fileName=hashMap.get("id").replaceAll("\"","")+".jpeg";
        ImageUtils.decodeBase64ToImage(frontimage,this.tmpDirFile,fileName);
        //-----------------------------将图片上传微信服务器素材--------------------------
        //上传图文消息内的图片获取URL,图片仅支持jpg/png格式，大小必须在1MB以下。
        File file =new File(this.tmpDirFile + fileName);
        WxMediaImgUploadResult imgUploadResult= null;
        try {
            imgUploadResult  = weixinService.getMaterialService().mediaImgUpload(file);
        } catch (WxErrorException e) {
            e.printStackTrace();
        }
        this.logger.info("\n-----------------微信上传图片成功:" + imgUploadResult.getUrl());
        hashMap.put("imgUploadUrl",imgUploadResult.getUrl());
        return hashMap;
    }

}

